<?php
namespace tpfcore\storage;
use Qiniu\Auth as Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Qiniu\Http\Client;
use Qiniu\Http\Error;
/**
 * ============================================================================
 * 版权所有 2017-2077 tpframe工作室，并保留所有权利。
 * @link http://www.tpframe.com/
 * @author    yaosean <510974211>
 * @copyright Copyright (c) 2017 TPFrame Software LLC
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * tpf标签主类
 */
class Qiniu{
	private $qnAuth=null;
	public $sdkinfo=[
		"accessKey"=>"",
		"secretKey"=>"",
		"bucket"=>"",
		"oss_img_url"=>""
	];

    public $error;

    public $uploadFileInfo;


    public function __construct($sdkinfo=[]){
    	if(is_array($sdkinfo) && !empty($sdkinfo)){
    		$this->sdkinfo = array_merge($this->sdkinfo,$sdkinfo);
    	}

    	if(empty($this->sdkinfo['accessKey']) || empty($this->sdkinfo['secretKey'])){

    		throw new \Exception("请先配置好accessKey或secretKey后再试");
    		
    	}

    	try{
    		$this->qnAuth=new Auth($this->sdkinfo['accessKey'], $this->sdkinfo['secretKey']);
    	}catch(OssException $e){
    		throw new \Exception($e->getMessage());
    	}
    }
    /**
	 * 简单上传
	 * $filename 上传到七牛云的地址文件
	 */
	public function putFile($bucket,$filename,$tmp_file)
	{   
        $token = $this->getuploadToken($bucket);

        try {
        	// 构建 UploadManager 对象
	        $uploadMgr = new UploadManager();

			list($ret, $err) = $result = $uploadMgr->putFile($token, $filename, $tmp_file);
	        if ($err !== null) {
	            $this->error = $e->getMessage();
	            return false;
	        } 
        } catch (Exception $e) {
        	$this->error = $e->getMessage();
	        return false;
        }
        return true;
	}

	public function getuploadToken($bucket){
		try {
			$token = $this->qnAuth->uploadToken($bucket);
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
		return $token;
	}

    /**
    * 获取bucket列表
    */
    public function listBucket(){

        $url="http://rs.qbox.me/buckets";

        $headers = $this->qnAuth->authorization($url);

        $ret = Client::get($url, $headers);

        if (!$ret->ok()) {
            $this->error = (new Error($url, $ret))->message();
            return false;
        }
        return array($ret->json(), null)[0];
    }

    /**
    * 创建bucket
    * @bucket string bucket名
    * @region string 创建区域标识   默认z0  华东
    */
    public function createBucket($bucket,$region="z0"){

        $bucket = \Qiniu\base64_urlSafeEncode($bucket);

        $url="http://rs.qiniu.com/mkbucketv2/$bucket/region/$region";

        $headers = $this->qnAuth->authorization($url);

        $ret = Client::post($url,"", $headers);

        if (!$ret->ok()) {
            $this->error = (new Error($url, $ret))->message();
            return false;
        }
        return true;

    }
    /**
    * 删除指定的bucket
    * @bucket string bucket名
    */
    public function deleteBucket($bucket){

        $url="http://rs.qiniu.com/drop/$bucket";

        $headers = $this->qnAuth->authorization($url);

        $ret = Client::post($url,"", $headers);

        if (!$ret->ok()) {
            $this->error = (new Error($url, $ret))->message();
            return false;
        }
        return true;
    }
    /**
    * 获取bucket空间域名
    * @bucket string bucket名
    */
    public function listBucketDomain($bucket){

        $url="http://api.qiniu.com/v6/domain/list?tbl=$bucket";

        $headers = $this->qnAuth->authorization($url);

        $ret = Client::get($url, $headers);

        if (!$ret->ok()) {
            $this->error = (new Error($url, $ret))->message();
            return false;
        }
        return array($ret->json(), null)[0];
    }

    /**
    * 设置 Bucket 访问权限
    * @bucket string bucket名
    */
    public function setBucketPriv($bucket,$private=0){

        $url="http://uc.qbox.me/private?bucket=$bucket&private=$private";

        $headers = $this->qnAuth->authorization($url);

        $ret = Client::post($url,"", $headers);

        if (!$ret->ok()) {
            $this->error = (new Error($url, $ret))->message();
            return false;
        }
        return true;
    }

    public function doBucketExist($bucket){
        $result = $this->listBucket();
        if(in_array($bucket, $result)){
            $this->error = "该bucket名已经存在";
            return true;
        }
        return false;
    }

	/**
     * 取得最后一次错误信息
     * @access public
     * @return string
     */
    public function getErrorMsg() {
        return $this->error;
    }
}